import React, { useState,useCallback, useContext } from "react";
import "./StudentForm.css";
import StuContext from '../store/StuContext';

function StudentForm(props) {
    const ctx = useContext(StuContext)
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    
    const [inputdata, setInputdata] = useState({
        name:props.isEdit ? props.stu.name:'',
        gender:props.isEdit ? props.stu.gender:'男',
        age:props.isEdit ? props.stu.age:'',
        address:props.isEdit ? props.stu.address:''
    })
    //数据改变绑定
    const ChangeHandler = (e,type) => {
        setInputdata((prevState) => {
            //深拷贝一次 要不然返回prevState地址相同不会render
            const newInputdata = {...prevState}
            newInputdata[type] = e.target.value
            return newInputdata
        })

    }
    //添加数据到数据库
    const addHandler = useCallback(async ()=> {
        try {
            setLoading(true)
            setError(null)
            
            const res = await fetch(`http://localhost:1337/api/students/`, {
                method:'post',
                headers: {
                    "Content-Type": 'application/json'
                },
                body: JSON.stringify({data:inputdata})
            })

            if(!res.ok){
                throw new Error('添加失败')
            }
            //请求数据成功渲染页面
            ctx.fetchData()
        } catch (e) {
            setError(e.message)
        }finally{
            setLoading(false)
        }
    },[ctx,inputdata])
    //更新用户数据
    const updateStu = useCallback(async(id, newStu) => {
        try{
            setError(null)
            setLoading(true)
            const res = await fetch(`http://localhost:1337/api/students/${id}`,{
                method:'put',
                body:JSON.stringify({data:newStu}),
                headers:{
                    "Content-type":"application/json"
                }
            })
            
            if(!res.ok){
                throw new Error('修改失败')
            }
            ctx.fetchData()
        }catch (e){
            setError(e.message)
        }finally {
            setLoading(false)
        }
    },[ctx])
    const updateHandler = ()=> {
        updateStu(props.stu.documentId,inputdata);
    }

    const stateText = props.isEdit?"修改":"添加";
    return (
        <>
        <tr className="student-form">
            {/* 姓名 */}
            <td>
                <input onChange={(e) => {ChangeHandler(e,"name")}}
                type="text"
                value={inputdata.name}
                />
            </td>
            {/* 性别 */}
            <td>
                <select
                    onChange={(e) => {ChangeHandler(e,"gender")}}
                    value={inputdata.gender}
                >
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </td>
            {/* 年龄 */}
            <td>
                <input onChange={(e) => {ChangeHandler(e,"age")}}
                type="text"
                value={inputdata.age}
                />
            </td>
            {/* 地址 */}
            <td>
                <input onChange={(e) => {ChangeHandler(e,"address")}}
                type="text" 
                value={inputdata.address}
                />
            </td>
            <td>
                {props.isEdit?<button onClick={props.onCancel}>取消</button>:""}
                <button onClick={props.isEdit?updateHandler:addHandler}>{stateText}</button>
            </td>
        </tr>
        {loading && <tr><td colSpan={5}>正在{stateText}数据</td></tr>}
        {error && <tr><td colSpan={5}>{stateText}失败</td></tr>}
        </>
    );
}

export default StudentForm;
